package com.gh.controller;

import com.gh.client.CoreUserInfoClient;
import com.gh.util.CodeUtil;
import com.gh.common.exception.Assert;
import com.gh.common.result.R;
import com.gh.common.result.ResponseEnum;
import com.gh.common.util.RegexValidateUtils;
import com.gh.service.SmsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author Eric
 * @Date 2021/9/11 9:15
 * @Version 1.0
 */
@Slf4j
@RestController
@RequestMapping("/api/sms")
public class SmsController {

    @Autowired
    private SmsService smsService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private CoreUserInfoClient coreUserInfoClient;

    @GetMapping("/send/{phone}")
    public R send(@PathVariable String phone) {
        //校验手机号码不为空
        Assert.notNull(phone, ResponseEnum.MOBILE_NULL_ERROR);
        //校验手机号码是否合法
        Assert.isTrue(RegexValidateUtils.checkCellphone(phone), ResponseEnum.MOBILE_ERROR);
        String code = (String) redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(code)) {
            log.info("验证码是redis中获取的" + code);
            return R.error().message("请五分钟后再试");
        }
        //判断手机号是否已经被注册
        R r = coreUserInfoClient.checkMobile(phone);
        Boolean isExist = (Boolean) r.getData().get("isExist");
        Assert.isTrue(isExist == false, ResponseEnum.MOBILE_EXIST_ERROR);

        Map<String, Object> map = new HashMap<>();
        code = CodeUtil.getCode();
        map.put("code", code);
        boolean isSend = smsService.sendCode(map, phone);
        if (isSend) {
            redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);
            log.info("验证码存入redis成功");
        }
        return R.ok().message("发送短信成功");
    }
}
